<?php

class Users extends Zend_Db_Table {

    protected $_name = 'jos_users';

    public function createCookie($remember, $user, $parent) {
        $time = time();
        $rand = rand(35000, 900000);
        $sesid = md5($time . $rand);

        if ($remember == 1) {

            setcookie("user", "$user", $time + 2592000);
            setcookie("sesid", "$sesid", $time + 2592000);
            $data = array(
                'sesid' => $sesid,
                'user' => $user,
                'parent' => $parent
            );
            $this->insert($data);
        } else {
            setcookie("user", "$user", $time + 3600);
            setcookie("sesid", "$sesid", $time + 3600);
            $data = array(
                'sesid' => $sesid,
                'user' => $user,
                'parent' => $parent
            );
            $this->insert($data);
        }
    }

    public function checkCookieCurrentDomain($sesid, $user) {
        if (!empty($sesid) && !empty($user)) {
            //$row = $this->fetchRow()->select()->where('user=?', $user);
            $row = $this->fetchRow("sesid='$sesid'");

            if ($row->user == $user) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    public function removeCookie($sesid) {
        $where = $this->getAdapter()->quoteInto('sesid=?', $sesid);
        $this->delete($where);
    }

    public function insertCookieToRouter() {
        $time = time();
        $rand = rand(35000, 900000);
        $sesid = md5($time . $rand);
        $hash = md5(rand(35000, 900000));
        $data = array(
            'sesid' => $sesid,
            'hash' => $hash,
            'user' => $user,
            'parent' => 0
        );
    }

    public function checkRouterCookie($domain) {
        $auth = Zend_Auth::getInstance();



        if ($auth->hasIdentity()) {
            $user = $auth->getIdentity()->email;
            $row = $this->fetchRow(select()->where('user=? AND parent=0', $user));
            return $row;
            //$this->_redirect("http://$domain/index/auth/id/{$row->id}/hash/{$row->hash}");
        } else {
            return 1;
            //$this->_redirect("http://$domain/index/auth/id/null/hash/null");
        }
    }

    public function createGuestCookie($parent) {
        $time = time();
        $rand = rand(35000, 900000);
        $sesid = md5($time . $rand);



        setcookie("user", "guest", $time + 1800, "/");
        setcookie("sesid", "$sesid", $time + 1800, "/");
        $data = array(
            'sesid' => $sesid,
            'user' => guest,
            'parent' => $parent
        );
        $this->insert($data);
//		Zend_Auth::getInstance()->getStorage()->write(array(
//			'rola' => 'guest'));
        return true;
        //$this->_redirect("http://$domain/");
    }

}
